package com.tdam2011.grupo02.ui;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import com.tdam2011.grupo02.data.ContactDroidSettings;
import com.tdam2011.grupo02.data.DatabaseHelperSingleton;
import com.tdam2011.grupo02.data.OnSendingInterface;
import com.tdam2011.grupo02.domain.ContactLocation;
import com.tdam2011.grupo02.domain.Mail;
import com.tdam2011.grupo02.domain.MensajeWeb;
import com.tdam2011.grupo02.domain.Usuario;
import com.tdam2011.grupo02.messagesender.WebServiceInfo;
import com.tdam2011.grupo02.messagesender.WebServiceSingleton;
import com.tdam2011.grupo02.support.LocationUpdateInterface;
import com.tdam2011.grupo02.support.MapLocationController;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class ContactActionController implements LocationUpdateInterface {

	private Context context;
	private ContactDroidSettings settings;
	private MapLocationController location;
	private ContactLocation cLocation;

	public ContactActionController(Context context) {
		this.context = context.getApplicationContext();
		settings = new ContactDroidSettings(this.context);
	}

	public void makeCall(String num) {
		try {
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse("tel:" + num));
			callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

			context.startActivity(callIntent);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void sendSMS(String num) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setType("vnd.android-dir/mms-sms");
		intent.setData(Uri.parse("smsto:" + num));

		context.startActivity(intent);
	}

	public void sendSMS(String num, String body) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setType("vnd.android-dir/mms-sms");
		intent.setData(Uri.parse("smsto:" + num));
		intent.putExtra("sms_body", body);

		context.startActivity(intent);
	}

	public void sendMail(String nombre, String mail) {
		ConnectivityManager connectivity;
		NetworkInfo wifiInfo, mobileInfo;

		connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		wifiInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		mobileInfo = connectivity
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

		if (wifiInfo.isConnected() || mobileInfo.isConnected()) {
			Uri uri = Uri.parse("mailto:" + mail);

			Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);

			Mail aux = new Mail();
			aux.setContacto(nombre);
			aux.setMailContacto(mail);
			Calendar rightNow = Calendar.getInstance();
			Long d = rightNow.getTimeInMillis();
			aux.setFecha(new Date(d));
			DatabaseHelperSingleton.getInstance(context).getDatabaseHelper()
					.addMail(aux);

		} else {
			Toast.makeText(context,
					"No esta conectado a internet para enviar el mail.",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void sendMsgWeb() {
		Intent intent = new Intent(context, MensajeWebComposicionActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		context.startActivity(intent);
	}

	public void sendMsgWebConnection(OnSendingInterface onSendingInterface,
			String contact, String message, boolean isUpdate) {
		Usuario user = DatabaseHelperSingleton.getInstance(context)
				.getDatabaseHelper().getUsuario();

		MensajeWeb msgw = new MensajeWeb();
		msgw.setContacto(contact);
		msgw.setMensaje(message);
		msgw.setTipo(MensajeWeb.TYPE_SENT);
		msgw.setOutbox(MensajeWeb.TYPE_INBOX);

		if (settings.isMsgwSendLocation()) {
			Log.d("DEMO", "################# LOCATION EN TRUE");
			if (location == null)
				location = new MapLocationController(context, this);

			if (cLocation != null) {
				msgw.setContactLocation(cLocation);
				Log.d("DEMO", "esta es la location del ocoton "
						+ msgw.getContactLocation().getAddress());
			} else
				msgw.setContactLocation(null);
		} else {
			Log.d("DEMO", "&&&&&&&&&&&&&&&&&&& LOCATION EN FALSE");
			msgw.setContactLocation(null);
		}

		new SendMessageAsyncTask(onSendingInterface, msgw, isUpdate).execute(
				user.get_id(), user.getPassword());

	}

	public void sendMsgWebNoConnection(OnSendingInterface onSendingInterface,
			String contact, String message) {

		MensajeWeb msgw = new MensajeWeb();
		Calendar date = Calendar.getInstance();

		msgw.setFecha(date.getTimeInMillis());
		msgw.setContacto(contact);
		msgw.setMensaje(message);
		msgw.setTipo(MensajeWeb.TYPE_SENT);
		msgw.setOutbox(MensajeWeb.TYPE_OUTBOX);

		DatabaseHelperSingleton.getInstance(context).getDatabaseHelper()
				.addMsgw(msgw);

	}

	public void sendMsgWebOutbox(LinkedList<MensajeWeb> msgws) {
		Usuario user = DatabaseHelperSingleton.getInstance(context)
				.getDatabaseHelper().getUsuario();

		WebServiceInfo result = null;

		for (MensajeWeb aux : msgws) {
			try {
				result = WebServiceSingleton.getInstance(user.get_id(),
						user.getPassword()).sendMessage(aux);
			} catch (Exception e) {
			}

			if (WebServiceInfo.SUCCESS == result.getCode()) {
				Calendar date = Calendar.getInstance();
				aux.setFecha(date.getTimeInMillis());
				aux.setOutbox(MensajeWeb.TYPE_INBOX);

				if (result != null
						&& WebServiceInfo.SUCCESS == result.getCode())
					aux.setOutbox(MensajeWeb.TYPE_INBOX);
				else
					aux.setOutbox(MensajeWeb.TYPE_OUTBOX);

				DatabaseHelperSingleton.getInstance(context)
						.getDatabaseHelper().updateMsgw(aux);
			}
		}

	}

	public void registerUser(OnSendingInterface onSendingInterface, Usuario user) {

		new RegisterUserAsyncTask(onSendingInterface, user).execute();

	}
	
	public void viewLog(String nombre, String numero, String id) {
		Intent intent = new Intent().setClass(context,
				HistorialLogFragmentActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("nombre", nombre);
		intent.putExtra("numero", numero);
		intent.putExtra("id", id);

		context.startActivity(intent);
	}

	/*************************** Send Web Message Async Task ***************************/

	class SendMessageAsyncTask extends
			AsyncTask<String, Integer, WebServiceInfo> {

		OnSendingInterface onSend;
		MensajeWeb msgw;
		boolean isUpdate;

		public SendMessageAsyncTask(OnSendingInterface onSend, MensajeWeb msgw,
				boolean isUpdate) {
			this.onSend = onSend;
			this.msgw = msgw;
			this.isUpdate = isUpdate;
		}

		@Override
		protected WebServiceInfo doInBackground(String... params) {
			onSend.onSending();
			WebServiceInfo result = null;

			try {
				result = WebServiceSingleton.getInstance(params[0], params[1])
						.sendMessage(msgw);
			} catch (Exception e) {
			}

			Calendar date = Calendar.getInstance();
			msgw.setFecha(date.getTimeInMillis());

			if (result != null && WebServiceInfo.SUCCESS == result.getCode())
				msgw.setOutbox(MensajeWeb.TYPE_INBOX);
			else
				msgw.setOutbox(MensajeWeb.TYPE_OUTBOX);

			if (isUpdate)
				DatabaseHelperSingleton.getInstance(context)
						.getDatabaseHelper().updateMsgw(msgw);
			else
				DatabaseHelperSingleton.getInstance(context)
						.getDatabaseHelper().addMsgw(msgw);

			return result;
		}

		@Override
		protected void onPostExecute(WebServiceInfo result) {
			super.onPostExecute(result);
			if (result != null && result.getType() != null
					&& result.getType().equals(WebServiceInfo.SUCCESS_MESSAGE)) {
				onSend.onSuccess();
			} else {
				onSend.onError();
			}
		}
	}

	/*************************** Register User Async Task ***************************/

	class RegisterUserAsyncTask extends
			AsyncTask<String, Integer, WebServiceInfo> {

		OnSendingInterface onSend;
		Usuario user;

		public RegisterUserAsyncTask(OnSendingInterface onSend, Usuario user) {
			this.onSend = onSend;
			this.user = user;
		}

		@Override
		protected WebServiceInfo doInBackground(String... params) {
			onSend.onSending();
			WebServiceInfo result = null;

			try {
				result = WebServiceSingleton.getInstance(user.get_id(),
						user.getPassword()).registerUser();
			} catch (Exception e) {
			}

			if (result != null && WebServiceInfo.SUCCESS == result.getCode()) {
				DatabaseHelperSingleton
						.getInstance(context)
						.getDatabaseHelper().addUser(user);
			}
			
			return result;
		}

		@Override
		protected void onPostExecute(WebServiceInfo result) {
			super.onPostExecute(result);
			if (result != null && result.getType() != null
					&& result.getType().equals(WebServiceInfo.SUCCESS_MESSAGE)) {
				onSend.onSuccess();
			} else {
				onSend.onError();
			}
		}
	}

	/***************************** LOCATION *****************************/

	@Override
	public void updateLocation(Location location) {
		if (location != null) {
			cLocation = new ContactLocation();
			cLocation.setLatitud(location.getLatitude());
			cLocation.setLongitude(location.getLongitude());
			cLocation.setAddress(MapLocationController
					.getContactLocationAddress(context, location.getLatitude(),
							location.getLongitude()));

			Log.d("DEMO",
					"EN UPDATE DE ACTION CONTROLLER = "
							+ cLocation.getLatitud());
		}
	}

	public ContactLocation getCurrentLocation() {
		return cLocation;
	}

}
